import socketserver
import sys
import threading

from Lib import Utils
from Lib.Server import server, TcpRequestHandler

config = Utils.GetIniFile("./config.ini")


def tcp_serve():
    socketserver.ThreadingTCPServer((server.host, server.port), TcpRequestHandler).serve_forever()


def all_user():
    import locals
    print(locals.list_client)


def sys_exit():
    sys.exit(0)


def cmd_help():
    for key in data_cmd_execute.keys():
        print(f"{Utils.LenStr(key)}{Utils.LenStr('::=>', 7)} {data_cmd_execute[key]['description']}")


def test(params):
    print(params)


def set_user_join_chat_channel(params):
    channel_name = params[0]
    user_id = int(params[1])
    import locals
    locals.CreateChannel(channel_name)
    if locals.JoinChannel(channel_name, user_id):
        print(f"{user_id} 加入频道 {channel_name}")


def all_chat_channel():
    import locals
    print(locals.list_channel)


data_cmd_execute = {
    "test": {
        "execute": test,
        "description": "测试"
    },
    "all": {
        "execute": all_user,
        "description": "显示所有用户"
    },
    "exit": {
        "execute": sys_exit,
        "description": "退出系统"
    },
    "?,help": {
        "execute": cmd_help,
        "description": "帮助"
    },
    "all_chat_channel": {
        "execute": all_chat_channel,
        "description": "显示所有聊天频道"
    },
    "user_join": {
        "execute": set_user_join_chat_channel,
        "description": "后台控制用户加入频道:{频道名称:str} {用户ID:int}"
    },
    "say_channel": {
        "description": "?频道聊天:{频道名称:str} {内容:str}"
    },
    "say": {
        "description": "?对某人说:{用户ID:int} {内容:str}"
    }
}


def cmd_execute(str_split=","):
    _str = "/"
    while True:
        try:
            str_cmd = input("")
            params = []
            has_cmd = False
            if str_cmd.startswith(_str):
                arr = str_cmd[len(_str):].split(" ")
                cmd = arr[0]
                _params = arr[1:]
                if cmd == "":
                    Utils.Console(f"指令输入错误", "error")
                for param in _params:
                    if Utils.IsNumber(param):
                        param = float(param)
                    elif "," in param:
                        param = eval(param)
                    params.append(param)

                for exe_cmd in data_cmd_execute.keys():
                    if str_split in exe_cmd:
                        cmd_arr = exe_cmd.split(str_split)
                        if cmd in cmd_arr:
                            has_cmd = True
                    else:
                        if cmd == exe_cmd:
                            has_cmd = True
                    if has_cmd:
                        Utils.Console(f"执行命令: {cmd}", "info")
                        if params:
                            data_cmd_execute[exe_cmd]['execute'](params)
                        else:
                            data_cmd_execute[exe_cmd]['execute']()
                        break
                if not has_cmd and cmd:
                    Utils.Console(f"找不到命令: {cmd}", "error")
            else:
                Utils.Console(f"输入: {str_cmd}", "debug")
        except:
            pass


list_thread = [
    threading.Thread(target=tcp_serve),
    threading.Thread(target=cmd_execute())
]

for thread in list_thread:
    thread.start()
